﻿using System;
using System.Linq;

namespace ECommerce.Administration.Controls
{
	public partial class EditShippingMethod : AdminBaseUsercontrol
	{
		Service.IShippingMethodService _ShippingMethodService;

		private int _ShippingMethodID;

		public int ShippingMethodID
		{
			get
			{
				if(ViewState["ShippingMethodID"] != null)
				{
					_ShippingMethodID = int.Parse(ViewState["ShippingMethodID"].ToString());
				}
				else
				{
					_ShippingMethodID = CommonHelper.QueryStringInt("shippingmethodid");
				}
				return _ShippingMethodID;
			}
			set
			{
				_ShippingMethodID = value;
				ViewState["ShippingMethodID"] = value;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				if (ShippingMethodID > 0)
				{
					LabelEditShippingMethodTitle.Text = GetLocalResourceString("Admin.EditShippingMethod.Edit.Title");
				}
				else
				{
					LabelEditShippingMethodTitle.Text = GetLocalResourceString("Admin.EditShippingMethod.Add.Title");
				}

				ButtonSave.Text = GetLocalResourceString("Admin.SaveButtonText");
				
				SetValues();
			}
		}

		protected void ButtonSave_Click(object sender, EventArgs e)
		{
			Data.Entity.ShippingMethod theShippingMethod = new Data.Entity.ShippingMethod();

			theShippingMethod.Description = TextDescription.Text.Trim();
			theShippingMethod.DisplayOrder = int.Parse(TextDisplayOrder.Text.Trim());
			theShippingMethod.IsActive = CheckIsActive.Checked;
			theShippingMethod.Name = TextShippingMethodName.Text.Trim();

			if (_ShippingMethodService == null)
			{
				_ShippingMethodService = new Service.ShippingMethodService();
			}

			if(ShippingMethodID > 0)
			{
				theShippingMethod.ShippingMethodID = ShippingMethodID;

				_ShippingMethodService.UpdateShippingMethod(theShippingMethod);
			}
			else
			{
				ShippingMethodID = _ShippingMethodService.CreateNewShippingMethod(theShippingMethod);
			}
		}

		private void SetValues()
		{
			if(ShippingMethodID > 0)
			{
				if (_ShippingMethodService == null)
				{
					_ShippingMethodService = new Service.ShippingMethodService();
				}

				var theShippingMethod = (from sm in _ShippingMethodService.GetAllShippingMethod()
										 where sm.ShippingMethodID.Equals(ShippingMethodID)
										 select sm).FirstOrDefault();

				TextShippingMethodName.Text = theShippingMethod.Name;
				TextDescription.Text = theShippingMethod.Description;
				TextDisplayOrder.Text = theShippingMethod.DisplayOrder.ToString();
				CheckIsActive.Checked = theShippingMethod.IsActive;
			}
		}
	}
}